Native Application Development with Android - Topic 4 Summary
1. Getting Started with Android Development
Android is the world's most popular mobile operating system, powering over 80% of smartphones and various other devices.
1.1 What is Android?
- Mobile OS based on Linux kernel
- User interface for touch screens
- Highly customizable for different devices
- Open source platform
- Over 2 million apps in Google Play Store
- Supports devices: smartphones, watches, TVs, cars
- Rich ecosystem of development tools and libraries
Key Challenges in Android Development:
- Multiple screen sizes & resolutions: Devices vary significantly in screen dimensions and pixel densities
- Performance: Apps must be responsive and smooth under various conditions
- Security: Protect user data and prevent unauthorized access
- Compatibility: Support older platform versions while leveraging new features
- Market understanding: Know your target audience and their device preferences
1.2 Setting Up Development Environment
Android Studio
Official IDE for Android development with features:
- Flexible Gradle-based build system
- Fast and feature-rich emulator
- Unified environment for all Android devices
- Apply Changes for quick code updates
- Code templates and GitHub integration
- Testing tools and frameworks
- Lint tools for performance and compatibility checks
- C++ and NDK support
Project Structure
| Folder |
Purpose |
| manifests/ |
AndroidManifest.xml - app description and permissions |
| java/ |
Java/Kotlin source code packages |
| res/ |
Resources (XML): layouts, strings, images, colors, dimensions |
| build.gradle |
Gradle build configuration files |
Gradle Build System
Modern build system that handles:
- Compilation and packaging
- Dependency management
- Resource processing
- Testing and deployment
Three build.gradle files:
- Project-level: Global configuration
- Module-level: App-specific configuration
- Settings: Project structure settings
Running Your App
- Connect physical device with USB debugging enabled
- Set up Android Virtual Device (AVD) in Android Studio
- Click "Run" button to deploy and test
- Use Logcat for debugging and monitoring app behavior
Logging in Android
Use Logcat to view system and app logs:
- Log levels: Verbose, Debug, Info, Warning, Error, Assert
- Common methods: Log.v(), Log.d(), Log.i(), Log.w(), Log.e()
- Best practice: Use meaningful tags for filtering
2. Working with User Interfaces
2.1 App Manifest and Resources
AndroidManifest.xml - Essential File:
Describes app components, permissions, and requirements to the Android system.
Key Manifest Elements
| Element |
Purpose |
Example |
| Activity |
Declares an Activity component |
<activity android:name=".MainActivity"> |
| Service |
Declares a Service component |
<service android:name=".MyService"> |
| BroadcastReceiver |
Declares a BroadcastReceiver component |
<receiver android:name=".MyReceiver"> |
| ContentProvider |
Declares a ContentProvider component |
<provider android:name=".MyProvider"> |
| uses-permission |
Requests system permissions |
<uses-permission android:name="android.permission.INTERNET"/> |
| uses-feature |
Specifies required hardware features |
<uses-feature android:name="android.hardware.camera"/> |
| intent-filter |
Defines how components can be started |
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> |
Alternative Resources
Create configuration-specific resource folders:
res/layout-land/ - Landscape layouts
res/values-es/ - Spanish language strings
res/drawable-hdpi/ - High-density images
2.2 Activities and Fragments
Activity: A single focused thing a user can do. Manages a window for UI placement.
Fragment: Reusable portion of UI that can be combined in different ways in Activities.
Creating an Activity
- Define layout in XML (res/layout/activity_main.xml)
- Create Activity class extending AppCompatActivity
- Connect Activity with Layout using setContentView()
- Declare Activity in AndroidManifest.xml
Sample Activity Code
// 1. Define layout in XML (activity_main.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello Android!" />
</RelativeLayout>
// 2. Create Activity class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 3. Set content view
setContentView(R.layout.activity_main);
}
}
// 4. Declare in AndroidManifest.xml
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Activity Lifecycle
Active/Running
→
Visible
→
Stopped/Hidden
→
Destroyed
Lifecycle Callbacks:
onCreate() → onStart() → onResume() → (active)
↓
onPause() → onStop() → onDestroy()
Activity States
| State |
Description |
System Behavior |
| Active/Running |
Foreground activity, user interaction |
All components active |
| Visible |
Partially obscured, still visible |
Retains state, active |
| Stopped/Hidden |
Completely obscured by another activity |
Retains state, may be killed |
| Destroyed |
Process terminated |
All resources released |
Three Key Loops
- Entire Lifetime: onCreate() → onDestroy() - Setup and cleanup
- Visible Lifetime: onStart() → onStop() - Maintain visible resources
- Foreground Lifetime: onResume() → onPause() - Active user interaction
2.3 Layouts, Adapters, Action Bar, Dialogs and Notifications
Views and View Groups
| Category |
Examples |
Purpose |
| View |
Button, TextView, EditText, ImageView |
Basic UI building blocks |
| ViewGroup |
ConstraintLayout, LinearLayout, RelativeLayout, FrameLayout |
Containers that hold and arrange Views |
| Adapter |
RecyclerView.Adapter, ArrayAdapter |
Bridges between data and Views |
Common Layout Classes
| Layout |
Description |
Use Case |
| ConstraintLayout |
Connects views with constraints to edges and other views |
Complex UIs with flexible positioning |
| LinearLayout |
Organizes views in horizontal or vertical row |
Simple lists or forms |
| RelativeLayout |
Positions views relative to each other |
Traditional Android layouts |
| GridLayout |
Organizes views in grid structure |
Tabular data display |
| FrameLayout |
Displays single child or stack of children |
Fragments, simple overlays |
| ScrollView |
Provides scrolling capability |
Content longer than screen height |
| RecyclerView |
Efficiently displays large datasets |
Lists, grids with dynamic data |
View Attributes
Common XML attributes:
| Attribute |
Description |
Example |
| android:id |
View identifier |
android:id="@+id/button1" |
| android:layout_width |
Width dimension |
android:layout_width="match_parent" |
| android:layout_height |
Height dimension |
android:layout_height="wrap_content" |
| android:text |
Display text |
android:text="@string/hello" |
| android:background |
Background color/resource |
android:background="@color/primary" |
| android:visibility |
Visibility state |
android:visibility="gone" |
Adapters
Role: Bridge between data source and View components like ListView or RecyclerView.
- Manages creating, updating, and destroying View items
- Handles data changes efficiently
- Examples: RecyclerView.Adapter, ArrayAdapter
Action Bar
- Primary toolbar within Activity
- Displays activity title and navigation
- Can include action buttons and menu items
- Key Methods:
getActionBar() - Get instance
setTitle(String) - Set title
inflateMenu(int) - Add menu items
Dialogs
Small windows that prompt user for decisions or additional information.
| Dialog Type |
Description |
Use Case |
| AlertDialog |
Shows title, message, up to 3 buttons, list items, or custom layout |
Confirmations, alerts |
| DatePickerDialog |
Predefined UI for date selection |
Calendar events, scheduling |
| TimePickerDialog |
Predefined UI for time selection |
Alarm clocks, timers |
| ProgressDialog |
Shows progress bar |
Waiting for operations |
Creating AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirmation")
.setMessage("Are you sure you want to delete?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Handle positive button click
}
})
.setNegativeButton("Cancel", null)
.show();
Notifications
Messages displayed outside regular app UI to inform users.
| Component |
Description |
| Notification Icon |
Small icon shown in status bar |
| Notification Title |
Brief description |
| Notification Text |
Detailed information |
| Notification Drawer |
Area where user can view all notifications |
Creating Notification
// Create notification channel (required for Android 8.0+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Important Notifications",
NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
// Build notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("New Message")
.setContentText("You have a new message from John")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// Show notification
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(NOTIFICATION_ID, builder.build());
3. Data and App Interaction
3.1 Intents and Broadcasts
Intent: Message object describing an action to perform, including data and component that should handle it.
Broadcast: System-wide message sent to interested components.
Intent Types
| Type |
Description |
Example |
| Explicit Intent |
Specifies exact component to start |
Intent intent = new Intent(this, TargetActivity.class); |
| Implicit Intent |
Describes action, system finds matching component |
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com")); |
Starting Activities
// Explicit intent
Intent explicitIntent = new Intent(this, TargetActivity.class);
startActivity(explicitIntent);
// Explicit intent with data
Intent dataIntent = new Intent(this, TargetActivity.class);
dataIntent.putExtra("key", "value");
startActivity(dataIntent);
// Implicit intent (e.g., open URL)
Intent implicitIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
startActivity(implicitIntent);
Broadcast Receivers
Components that respond to system-wide broadcasts.
- Static Declaration: Declared in AndroidManifest.xml
- Dynamic Registration: Registered at runtime
3.2 Preferences and Saving
- SharedPreferences: Simple key-value storage for app preferences
- Internal Storage: Private app storage
- External Storage: Shared storage (requires permissions)
- SQLite Database: Structured data storage
SharedPreferences Example
// Save preference
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "john_doe");
editor.putInt("score", 100);
editor.apply();
// Retrieve preference
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String username = prefs.getString("username", "default");
int score = prefs.getInt("score", 0);
3.3 Content Providers and Services
Content Providers
Manage access to shared data between apps. Standardized interface for CRUD operations.
- Built on SQLite database
- Implements URI-based access
- Requires permission declaration
Services
Background components that perform long-running operations.
- Started Service: Runs until explicitly stopped
- Bound Service: Runs as long as bound components exist
- Foreground Service: Shows notification, runs indefinitely
Creating a Service
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Perform background work
return START_STICKY; // Restart if killed
}
@Override
public IBinder onBind(Intent intent) {
return null; // Not a bound service
}
}
// Start service
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
3.4 AsyncTask and AsyncTaskLoader
Handles background operations and UI updates.
AsyncTask Lifecycle
private class MyTask extends AsyncTask
{
@Override
protected void onPreExecute() {
// UI setup before task
}
@Override
protected Result doInBackground(Params... params) {
// Background work
return result;
}
@Override
protected void onProgressUpdate(Progress... values) {
// Update progress UI
}
@Override
protected void onPostExecute(Result result) {
// Update UI with result
}
}
4. Sensors and Communication
4.1 Sensors
Sensor Types
| Sensor Type |
Description |
Example Use |
| Accelerometer |
Measures acceleration force |
Shaking gestures, tilt detection |
| Gyroscope |
Measures rotation |
Orientation tracking, gaming |
| Magnetometer |
Measures magnetic field |
Compass, magnetic detection |
| Light |
Measures ambient light |
Auto-brightness adjustment |
| Proximity |
Measures distance to object |
Phone call screen turns off |
| Temperature |
Measures ambient temperature |
Weather apps |
Registering Sensor Listener
// Get SensorManager
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get default sensor
Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// Register listener
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
// Implement callback
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
// Handle sensor data
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Handle accuracy change
}
4.2 Orientation and Movement
- Combine accelerometer and magnetometer data
- Calculate device orientation (azimuth, pitch, roll)
- Use SensorManager.getOrientation() or Sensor.TYPE_ROTATION_VECTOR
4.3 Sending and Receiving SMS
Requires SEND_SMS permission.
Sending SMS
// Check permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS}, REQUEST_SMS);
} else {
sendSMS("+1234567890", "Hello from my app!");
}
private void sendSMS(String phoneNumber, String message) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
}
5. Quick Reference Guide
Essential Files and Components
| File/Component |
Purpose |
Key Methods/Attributes |
| AndroidManifest.xml |
App configuration and permissions |
<activity>, <service>, <uses-permission> |
| Activity |
User interface screen |
onCreate(), setContentView(), setTitle() |
| Fragment |
Reusable UI component |
onCreateView(), onAttach() |
| Service |
Background processing |
onStartCommand(), onBind() |
| BroadcastReceiver |
System event handler |
onReceive() |
| ContentProvider |
Data sharing between apps |
query(), insert(), update(), delete() |
| Layout XML |
User interface definition |
<LinearLayout>, <TextView>, android:layout_width |
Common Layout Patterns
| Pattern |
Layout |
Use Case |
| Single screen |
ConstraintLayout |
Standard app screens |
| List |
RecyclerView |
Scrollable lists with dynamic data |
| Form |
LinearLayout + EditText |
Data entry screens |
| Card-based |
RecyclerView with CardView items |
Gallery, product listings |
Development Best Practices
- Follow Android design guidelines (Material Design)
- Handle configuration changes properly
- Use ViewModel and LiveData for lifecycle-aware components
- Implement proper error handling
- Optimize performance and memory usage
- Test on multiple devices and Android versions
- Use logging for debugging and monitoring
- Implement proper security measures for data and permissions
6. Exam Preparation Tips
- Memorize Activity lifecycle: Understand the four states and six callbacks
- Review AndroidManifest.xml structure: Know key elements and attributes
- Practice creating simple apps: Start with Hello World, then add screens and features
- Understand View hierarchy: Know how to create and modify layouts
- Study Intent types and usage: Know the difference between explicit and implicit intents
- Review resource management: Know how to use resources and alternative resources
- Practice with common UI components: Buttons, TextViews, RecyclerView, Dialogs
- Understand background processing: Know when to use AsyncTask, Services, or WorkManager
- Review sensor basics: Know how to register and use sensors
- Understand Android architecture components: ViewModel, LiveData, Room (from previous topics)
7. Summary and Key Takeaways
Android development requires understanding the platform architecture, user interface design, and app lifecycle management.
Essential components: Activities, Fragments, Services, BroadcastReceivers, and ContentProviders form the building blocks of Android apps.
UI development: Views and ViewGroups create the visual interface, with adapters handling data binding for lists and grids.
Data management: SharedPreferences, SQLite, ContentProviders, and Services handle data persistence and background processing.
System integration: Intents enable app-to-app communication and system feature access.
Sensor integration: Android's rich sensor framework enables innovative apps that respond to the physical world.
Best practices: Follow Android design guidelines, handle lifecycle properly, optimize performance, and test thoroughly.